#!/bin/bash

#定义变量
LOG_FILE="./log/access.log"
BLACKLIST_FILE="./blacklist/blacklist.conf"
THRESHOLD=10

# 获取当前时间的一分钟前的时间戳
TIME_THRESHOLD=$(date -d '1 minute ago' '+%Y-%m-%d %H:%M')

# 从 access.log 中获取一分钟内的所有记录，并统计每个 IP 的访问次数
COUNT_MAP=$(awk -v threshold="$TIME_THRESHOLD" -v threshold_date="$(date -d '1 minute ago' '+%d/%b/%Y:%H:%M')" '$4 > threshold_date {print $1}' $LOG_FILE | sort | uniq -c)

# 检查访问次数是否超过阈值，若超过则将 IP 添加到黑名单文件中
while read line; do
    count=$(echo $line | awk '{print $1}')
    ip=$(echo $line | awk '{print $2}')
    if ((count >= THRESHOLD)); then
        if ! grep -q "^$ip$" "$BLACKLIST_FILE"; then
            echo $ip >> $BLACKLIST_FILE
        fi
    fi
done <<< "$COUNT_MAP"

